package c2.cross.business.guildwar.rank;

import c2.cross.business.base.CrossSubModule;
import c2.cross.business.guildwar.GuildWarModule;
import cate.game.pvp.guildwar.data.rank.GWRoleRank;
import cate.game.role.RoleSnapshot;
import easy.java.dev.note.NoteClass;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Comparator;
import java.util.List;


@NoteClass("公会战玩家排行榜子模块")
@Slf4j
public class GuildWarRoleRankModule extends CrossSubModule<GuildWarModule> {

    @Getter
    private List<GWRoleRank> list;


    @Override
    public void initDependent() throws Exception {
        super.initDependent();
        this.list = useDb().guildWar.getRoleList();
    }


    @Override
    public void onShutdown() throws Exception {
        super.onShutdown();
        save();
    }

    public synchronized void clearList() {
        this.list.clear();
    }

    private static final int RANK_MAX = 100;

    public synchronized void record(RoleSnapshot snapshot, long newValue) {
        // 是否已经上榜
        GWRoleRank his = findRankByUid(snapshot.uid);
        if (his != null) {
            his.owner = snapshot.copy();
        }
        if (list.size() >= RANK_MAX) {
            GWRoleRank last = list.get(list.size() - 1);
            if (last.value > newValue) {
                // 没有进排行榜
                return;
            }
        }
        if (his != null) {
            his.read(snapshot, newValue);
        } else {
            GWRoleRank rank = new GWRoleRank(snapshot, newValue);
            if (list.size() >= RANK_MAX) {
                list.remove(list.size() - 1);
            }
            list.add(rank);
        }
        list.sort(Comparator.comparing((GWRoleRank a) -> -a.value).thenComparing(a -> a.recordTime));
    }

    public GWRoleRank findRankByUid(String roleUid) {
        try {
            for (GWRoleRank rank : list) {
                if (StringUtils.equals(roleUid, rank.owner.uid)) {
                    return rank;
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    public int getRankIndex(String uid) {
        try {
            for (int i = 0; i < list.size(); i++) {
                GWRoleRank rank = list.get(i);
                if (StringUtils.equals(rank.owner.uid, uid)) {
                    return i + 1;
                }
            }
            return -1;
        } catch (Exception e) {
            return -1;
        }
    }

    public void save() {
        useDb().guildWar.updateRankList(list);
    }

}
